package logic

import (
	"api/model/discountmember"
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCurDiscountListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCurDiscountListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCurDiscountListLogic {
	return &GetCurDiscountListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 获取用户当前支付商家的折扣卡
func (l *GetCurDiscountListLogic) GetCurDiscountList(req *types.RquestGetCurBusDiscount) (resp *types.ResponseUserDiscountList, err error) {

	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	discountMemberModel := discountmember.NewDiscountMemberModel(conn)

	openId := ""
	if req.WxOpenId != "" {
		openId = req.WxOpenId
	} else if req.AliOpenId != "" {
		openId = req.AliOpenId
	} else {
		return &types.ResponseUserDiscountList{
			Code: 400,
		}, nil
	}
	list, err := discountMemberModel.ListByBusId(l.ctx, int64(req.BusinessId), openId)

	if (*list) == nil {
		arr := make([]types.DicountMember, len(*list))

		var d = &types.DicountMember{}

		balance := 0
		for index, item := range *list {
			balance = balance + int(item.Balance)

			d.Discount = int(item.Discount)
			d.Balance = int(item.Balance)
			d.BusinessId = item.BusinessId

			arr[index] = *d
		}

		return &types.ResponseUserDiscountList{
			Code:    200,
			List:    arr,
			Balance: balance,
		}, nil

	}
	return &types.ResponseUserDiscountList{
		Code:    200,
		List:    nil,
		Balance: 0,
	}, nil

}
